<template>
  <div class="search-page">
    <!-- 搜索头部 -->
    <header class="search-header">
      <div class="container">
        <!-- 面包屑导航 -->
        <el-breadcrumb class="search-breadcrumb">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>搜索结果</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 搜索框 -->
        <div class="search-container">
          <div class="search-input-wrapper">
            <el-input
              v-model="searchKeyword"
              placeholder="输入关键词搜索科技资讯..."
              size="large"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
              @clear="handleClear"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleSearch"
              :loading="articlesStore.loading"
              class="search-button"
            >
              搜索
            </el-button>
          </div>
          
          <!-- 搜索建议 -->
          <div v-if="showSuggestions && suggestions.length > 0" class="search-suggestions">
            <div class="suggestions-title">热门搜索</div>
            <div class="suggestions-list">
              <el-tag
                v-for="suggestion in suggestions"
                :key="suggestion"
                @click="searchSuggestion(suggestion)"
                class="suggestion-tag"
              >
                {{ suggestion }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- 搜索结果 -->
    <section class="search-results">
      <div class="container">
        <!-- 搜索状态 -->
        <div class="search-status">
          <div v-if="hasSearched && !articlesStore.loading" class="results-info">
            <span v-if="searchResults.length > 0" class="results-count">
              找到 <span class="highlight">{{ searchResults.length }}</span> 篇关于 
              "<span class="highlight">{{ currentKeyword }}</span>" 的文章
            </span>
            <span v-else class="no-results">
              没有找到关于 "<span class="highlight">{{ currentKeyword }}</span>" 的文章
            </span>
          </div>
          
          <!-- 搜索筛选 -->
          <div v-if="searchResults.length > 0" class="search-filters">
            <div class="filter-group">
              <span class="filter-label">分类筛选：</span>
              <el-select 
                v-model="selectedCategory" 
                placeholder="所有分类"
                clearable
                @change="handleCategoryFilter"
                class="category-select"
              >
                <el-option 
                  v-for="category in availableCategories" 
                  :key="category"
                  :label="category" 
                  :value="category"
                />
              </el-select>
            </div>
            
            <div class="filter-group">
              <span class="filter-label">排序方式：</span>
              <el-radio-group v-model="sortBy" @change="handleSortChange" size="small">
                <el-radio-button value="relevance">相关性</el-radio-button>
                <el-radio-button value="latest">最新</el-radio-button>
                <el-radio-button value="popular">热门</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>

        <!-- 文章列表 -->
        <div 
          v-loading="articlesStore.loading"
          class="articles-container"
        >
          <NewsCard 
            v-for="article in filteredResults" 
            :key="article.id"
            :article="article"
            class="search-result-item"
          />
        </div>

        <!-- 无搜索结果 -->
        <div v-if="hasSearched && !articlesStore.loading && searchResults.length === 0" class="no-results-content">
          <div class="no-results-wrapper">
            <el-icon size="64"><Search /></el-icon>
            <h3>未找到相关内容</h3>
            <p>试试其他关键词，或者浏览我们的热门分类</p>
            
            <!-- 推荐搜索 -->
            <div class="recommended-searches">
              <p class="recommend-title">推荐搜索：</p>
              <div class="recommend-tags">
                <el-tag
                  v-for="tag in recommendedTags"
                  :key="tag"
                  @click="searchSuggestion(tag)"
                  class="recommend-tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
            
            <el-button type="primary" @click="goHome">返回首页</el-button>
          </div>
        </div>

        <!-- 搜索提示 -->
        <div v-if="!hasSearched && !articlesStore.loading" class="search-tips">
          <div class="tips-wrapper">
            <el-icon size="48"><Star /></el-icon>
            <h3>开始搜索</h3>
            <p>输入关键词查找感兴趣的科技资讯</p>
            
            <!-- 热门标签 -->
            <div class="hot-tags">
              <p class="tags-title">热门标签：</p>
              <div class="tags-list">
                <el-tag
                  v-for="tag in hotTags"
                  :key="tag"
                  @click="searchSuggestion(tag)"
                  class="hot-tag"
                  :style="{ '--tag-color': getRandomColor() }"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Search, Star } from '@element-plus/icons-vue'
import NewsCard from '@/components/NewsCard.vue'
import { useArticlesStore } from '@/stores/articles'
import { getRandomColor } from '@/utils'

const route = useRoute()
const router = useRouter()
const articlesStore = useArticlesStore()

const searchKeyword = ref('')
const currentKeyword = ref('')
const selectedCategory = ref('')
const sortBy = ref<'relevance' | 'latest' | 'popular'>('relevance')
const hasSearched = ref(false)
const showSuggestions = ref(false)

// 搜索建议和热门标签
const suggestions = ref([
  'ChatGPT', 'AI', '人工智能', '区块链', 'Bitcoin', 'iPhone', 'Tesla'
])

const hotTags = ref([
  'OpenAI', 'GPT-4', '机器学习', '深度学习', 'Web3', 'DeFi', 
  'NFT', '5G', '物联网', '自动驾驶', '芯片', '量子计算'
])

const recommendedTags = ref([
  '人工智能', '区块链技术', '智能手机', '电动汽车', '芯片技术', '5G网络'
])

const searchResults = computed(() => articlesStore.searchResults)

const availableCategories = computed(() => {
  const categories = new Set(searchResults.value.map(article => article.category))
  return Array.from(categories)
})

const filteredResults = computed(() => {
  let results = [...searchResults.value]
  
  // 分类筛选
  if (selectedCategory.value) {
    results = results.filter(article => article.category === selectedCategory.value)
  }
  
  // 排序
  switch (sortBy.value) {
    case 'latest':
      return results.sort((a, b) => b.publishTime - a.publishTime)
    case 'popular':
      return results.sort((a, b) => b.readCount - a.readCount)
    case 'relevance':
    default:
      // 相关性排序（简单实现：标题匹配度）
      const keyword = currentKeyword.value.toLowerCase()
      return results.sort((a, b) => {
        const aScore = (a.title.toLowerCase().includes(keyword) ? 2 : 0) + 
                      (a.summary.toLowerCase().includes(keyword) ? 1 : 0)
        const bScore = (b.title.toLowerCase().includes(keyword) ? 2 : 0) + 
                      (b.summary.toLowerCase().includes(keyword) ? 1 : 0)
        return bScore - aScore
      })
  }
})

onMounted(() => {
  // 从URL参数获取搜索关键词
  const urlKeyword = route.query.q as string
  if (urlKeyword) {
    searchKeyword.value = urlKeyword
    handleSearch()
  }
  
  // 初始化数据
  articlesStore.initializeData()
})

watch(() => route.query.q, (newKeyword) => {
  if (newKeyword && newKeyword !== searchKeyword.value) {
    searchKeyword.value = newKeyword as string
    handleSearch()
  }
})

const handleSearch = async () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) return
  
  currentKeyword.value = keyword
  hasSearched.value = true
  showSuggestions.value = false
  
  // 更新URL
  router.replace({ query: { q: keyword } })
  
  // 执行搜索
  await articlesStore.searchArticles(keyword)
}

const handleClear = () => {
  searchKeyword.value = ''
  currentKeyword.value = ''
  hasSearched.value = false
  showSuggestions.value = false
  articlesStore.clearSearch()
  router.replace({ query: {} })
}

const searchSuggestion = (suggestion: string) => {
  searchKeyword.value = suggestion
  handleSearch()
}

const handleCategoryFilter = () => {
  // 分类筛选逻辑已在computed中实现
}

const handleSortChange = () => {
  // 排序逻辑已在computed中实现
}

const goHome = () => {
  router.push('/')
}

// 监听搜索框聚焦状态
const handleSearchFocus = () => {
  if (!searchKeyword.value && !hasSearched.value) {
    showSuggestions.value = true
  }
}

const handleSearchBlur = () => {
  // 延迟隐藏建议，让用户有时间点击
  setTimeout(() => {
    showSuggestions.value = false
  }, 200)
}
</script>

<style scoped lang="scss">
.search-page {
  min-height: 100vh;
  background: var(--tech-bg-primary);
}

.search-header {
  padding: 40px 0;
  background: linear-gradient(135deg, var(--tech-bg-secondary), var(--tech-bg-primary));
  
  .search-breadcrumb {
    margin-bottom: 32px;
    
    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        color: var(--tech-text-secondary);
        
        &:hover {
          color: var(--tech-accent-neon);
        }
      }
      
      &:last-child .el-breadcrumb__inner {
        color: var(--tech-text-primary);
      }
    }
  }
  
  .search-container {
    position: relative;
    max-width: 600px;
    margin: 0 auto;
    
    .search-input-wrapper {
      display: flex;
      gap: 12px;
      
      .search-input {
        flex: 1;
        
        :deep(.el-input__wrapper) {
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(0, 212, 255, 0.3);
          backdrop-filter: blur(10px);
          border-radius: 8px;
          
          &:hover, &.is-focus {
            border-color: var(--tech-accent-neon);
            box-shadow: 0 0 0 1px rgba(0, 212, 255, 0.2);
          }
        }
        
        :deep(.el-input__inner) {
          color: var(--tech-text-primary);
          font-size: 16px;
          
          &::placeholder {
            color: var(--tech-text-muted);
          }
        }
      }
      
      .search-button {
        background: var(--tech-gradient-primary);
        border: none;
        padding: 0 24px;
        font-size: 16px;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 212, 255, 0.3);
        }
      }
    }
    
    .search-suggestions {
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
      margin-top: 8px;
      padding: 16px;
      background: rgba(21, 21, 32, 0.95);
      border: 1px solid rgba(0, 212, 255, 0.2);
      border-radius: 8px;
      backdrop-filter: blur(10px);
      z-index: 10;
      
      .suggestions-title {
        font-size: 12px;
        color: var(--tech-text-muted);
        margin-bottom: 8px;
      }
      
      .suggestions-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .suggestion-tag {
          cursor: pointer;
          background: rgba(0, 212, 255, 0.1);
          border: 1px solid rgba(0, 212, 255, 0.3);
          color: var(--tech-accent-neon);
          
          &:hover {
            background: rgba(0, 212, 255, 0.2);
            transform: translateY(-1px);
          }
        }
      }
    }
  }
}

.search-results {
  padding: 40px 0;
  
  .search-status {
    margin-bottom: 32px;
    
    .results-info {
      margin-bottom: 24px;
      
      .results-count, .no-results {
        font-size: 16px;
        color: var(--tech-text-secondary);
        
        .highlight {
          color: var(--tech-accent-neon);
          font-weight: 600;
        }
      }
    }
    
    .search-filters {
      display: flex;
      gap: 32px;
      align-items: center;
      padding: 16px;
      background: rgba(255, 255, 255, 0.02);
      border-radius: 8px;
      border: 1px solid rgba(0, 212, 255, 0.1);
      
      .filter-group {
        display: flex;
        align-items: center;
        gap: 12px;
        
        .filter-label {
          font-size: 14px;
          color: var(--tech-text-secondary);
          white-space: nowrap;
        }
        
        .category-select {
          width: 120px;
          
          :deep(.el-select__wrapper) {
            background: transparent;
            border: 1px solid rgba(0, 212, 255, 0.3);
          }
        }
        
        :deep(.el-radio-group) {
          .el-radio-button {
            .el-radio-button__inner {
              background: transparent;
              border: 1px solid rgba(0, 212, 255, 0.3);
              color: var(--tech-text-secondary);
              font-size: 12px;
              
              &:hover {
                color: var(--tech-accent-neon);
                border-color: var(--tech-accent-neon);
              }
            }
            
            &.is-active .el-radio-button__inner {
              background: var(--tech-gradient-primary);
              border-color: var(--tech-accent-neon);
              color: white;
            }
          }
        }
      }
    }
  }
  
  .articles-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 24px;
    
    .search-result-item {
      animation: fadeInUp 0.5s ease forwards;
    }
  }
  
  .no-results-content {
    text-align: center;
    padding: 80px 20px;
    
    .no-results-wrapper {
      .el-icon {
        color: var(--tech-text-muted);
        margin-bottom: 24px;
      }
      
      h3 {
        font-size: 20px;
        color: var(--tech-text-primary);
        margin-bottom: 12px;
      }
      
      p {
        font-size: 14px;
        color: var(--tech-text-secondary);
        margin-bottom: 32px;
      }
      
      .recommended-searches {
        margin-bottom: 32px;
        
        .recommend-title {
          font-size: 14px;
          color: var(--tech-text-secondary);
          margin-bottom: 12px;
        }
        
        .recommend-tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          justify-content: center;
          
          .recommend-tag {
            cursor: pointer;
            background: rgba(57, 255, 20, 0.1);
            border: 1px solid rgba(57, 255, 20, 0.3);
            color: var(--tech-accent-green);
            
            &:hover {
              background: rgba(57, 255, 20, 0.2);
              transform: translateY(-1px);
            }
          }
        }
      }
    }
  }
  
  .search-tips {
    text-align: center;
    padding: 80px 20px;
    
    .tips-wrapper {
      .el-icon {
        color: var(--tech-accent-neon);
        margin-bottom: 24px;
      }
      
      h3 {
        font-size: 20px;
        color: var(--tech-text-primary);
        margin-bottom: 12px;
      }
      
      p {
        font-size: 14px;
        color: var(--tech-text-secondary);
        margin-bottom: 32px;
      }
      
      .hot-tags {
        .tags-title {
          font-size: 14px;
          color: var(--tech-text-secondary);
          margin-bottom: 16px;
        }
        
        .tags-list {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
          justify-content: center;
          
          .hot-tag {
            cursor: pointer;
            background: linear-gradient(135deg, 
              rgba(var(--tag-color), 0.2), 
              rgba(var(--tag-color), 0.1)
            );
            border: 1px solid rgba(var(--tag-color), 0.4);
            color: var(--tech-text-primary);
            transition: all var(--tech-transition-normal) ease;
            
            &:hover {
              background: linear-gradient(135deg, 
                rgba(var(--tag-color), 0.3), 
                rgba(var(--tag-color), 0.2)
              );
              box-shadow: 0 0 12px rgba(var(--tag-color), 0.6);
              transform: translateY(-2px);
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .search-header {
    padding: 24px 0;
    
    .search-container {
      .search-input-wrapper {
        flex-direction: column;
        gap: 8px;
        
        .search-button {
          width: 100%;
        }
      }
    }
  }
  
  .search-results {
    .search-status {
      .search-filters {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
      }
    }
    
    .articles-container {
      grid-template-columns: 1fr;
      gap: 16px;
    }
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>